<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require_once("../conn.php");

$picurl = checkTrim($_POST['picurl']);
$titleurl = checkTrim($_POST['titleurl']);
$code = checkTrim($_POST['code']);
$price = checkTrim($_POST['price']);
$goodprice = checkTrim($_POST['goodprice']);
$musicurl = checkTrim($_POST['musicurl']);
$name = checkTrim($_POST['name']);
$isModify = $_POST['isModify'];

$db = new DBC();
$is_code_exist = false;
if ($isModify == 1) {
    $sql = "UPDATE t_hibaby_title_xml SET price = '" . $price . "',goodprice = '" . $goodprice . "',titleurl = '" . $titleurl . "',name = '" . $name . "',musicurl = '" . $musicurl . "',picurl = '" . $picurl . "' WHERE code = '" . $code . "'";
} else {
    $sql = "SELECT id FROM t_hibaby_xml WHERE code = '" . $code . "'";
    $data = $db->fetchData($sql);
    if ($data != null && count($data) > 0) {
        $is_code_exist = true;
    }
    $sql = "INSERT INTO t_hibaby_title_xml(code,name,price,goodprice,titleurl,musicurl,picurl,createTime) VALUES('" . $code . "','" . $name . "','" . $price . "','" . $goodprice . "','" . $titleurl . "','" . $musicurl . "','" . $picurl . "',now())";
}
if ($is_code_exist) {
    $msg = "编号 " . $code . " 已经存在。";
    echo "<script language='javascript'>alert('" . $msg . "'); </script>";
    echo "<script language='javascript'>history.back();</script>";
} else {
    $transfer = "titlePacketXMLList.php?menu=titleXML";
    if ($db->execute($sql)) {
        createXML($code, $name, $price, $goodprice, $titleurl, $musicurl, $picurl);
        //success
        echo "<script language='javascript'>location='" . $transfer . "';</script>";
    } else {
        //failue
        echo "<script language='javascript'>alert('失败'); </script>";
        echo "<script language='javascript'>history.back();</script>";
    }
}

function createXML($code, $name, $price, $goodprice, $titleurl, $musicurl, $picurl) {
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    $xml = $xml . '<title xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';    
    $xml = $xml . '<code>' . $code . '</code>';
    $xml = $xml . '<name>' . $name . '</name>';
    $xml = $xml . '<price>' . $price . '</price>';
    $xml = $xml . '<goodprice>' . $goodprice . '</goodprice>';
    $xml = $xml . '<titleurl>' . $titleurl . '</titleurl>';
    $xml = $xml . '<musicurl>' . $musicurl . '</musicurl>';
    $xml = $xml . '<picurl>' . $picurl . '</picurl>';
    $xml = $xml . '</title>';    
    if (!file_exists("title")) {
        mkdir("title");
    }
    $filename = "title/" . $code . ".xml";
    $file = fopen($filename, "w");
    fwrite($file, $xml);
    fclose($file);
}

function checkTrim($item) {
    if (isset($item)) {
        $item = trim($item);
    } else {
        $item = "";
    }
    return $item;
}
?>
